package com.mainbo.modular.system.controller.user;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.mainbo.core.common.constant.ApolloConstants;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.excel.ExcelBatchService;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.ClassUserMessage;
import com.mainbo.modular.system.dao.PtClassUserMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.Student;
import com.mainbo.modular.system.model.meta.*;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.ExportInfoVo;
import com.mainbo.modular.system.service.IPtAccountService;
import com.mainbo.modular.system.service.IPtAreaService;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2020-02-22 16:04:31
 */
@Controller
@RequestMapping("/ptStudent")
public class PtStudentController extends BaseController {
    private final static Logger logger= LoggerFactory.getLogger(PtStudentController.class);

    private String PREFIX = "/system/ptStudent/";

    @Autowired
    private StudentService studentService;
    @Autowired
    private IPtOrgService ptOrgService;
    @Resource
    private IPtAreaService ptAreaService;
    @Resource
    private IPtAccountService accountService;
    @Resource(name = "batchExportUserServiceImpl")
    private ExcelBatchService batchExportUserService;
    @Resource
    private PtClassUserMapper classUserMapper;
    @Autowired
    private JmsService jmsService;
    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(Model model) {
        PtOrg org =ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {
            model.addAttribute("orgId","0");
            return PREFIX + "ptStudent_org.html";
        }
        model.addAttribute("org",org);
        return PREFIX + "ptStudent_list.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptStudent_add")
    public String ptStudentAdd(String orgId, Model model) {
        PtOrg org=ptOrgService.selectById(orgId);
        model.addAttribute("org",org);
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPolitical", GBPolitical.values());
        model.addAttribute("poorStudentTypes", MetaUtils.listMeta(ConfigConstants.SYS_POOR_STUDENT_CODE));
        return PREFIX + "ptStudent_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptStudent_update/{ptStudentId}")
    public String ptStudentUpdate(@PathVariable String ptStudentId, Model model) {
        Student ptStudent = studentService.selectById(ptStudentId);
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        model.addAttribute("item",ptStudent);
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPolitical", GBPolitical.values());
        model.addAttribute("poorStudentTypes", MetaUtils.listMeta(ConfigConstants.SYS_POOR_STUDENT_CODE));
        LogObjectHolder.me().set(ptStudent);
        return PREFIX + "ptStudent_edit.html";
    }
    /**
     * 跳转到查看
     */
    @RequestMapping("/ptStudent_showInfo/{id}")
    public String ptStudentShowInfo(@PathVariable String id, Model model) {
        Student student=studentService.selectById(id);
        PtAccount account=accountService.selectById(id);
        student.setAccount(account.getAccount());
        model.addAttribute("item",student);
        model.addAttribute("sex", GBSex.forCname(student.getSex()));
        model.addAttribute("nation", GBNation.forCname(student.getNationCode()));
        if (StringUtils.isBlank(student.getPoliticalStatus())){
            model.addAttribute("GBPolitical","");
        }else {
            model.addAttribute("GBPolitical", GBPolitical.forCname(Integer.valueOf(student.getPoliticalStatus())));
        }
        if(student.getPoorType()!=null){
            Meta meta= MetaUtils.getMeta(ConfigConstants.SYS_POOR_STUDENT_CODE, String.valueOf(student.getPoorType()));
            model.addAttribute("poorStudentType",meta.getName());
        }else {
            model.addAttribute("poorStudentType","");
        }
        LogObjectHolder.me().set(student);
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());

        return PREFIX + "ptStudent_view.html";
    }
    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Student student) {

        if (StringUtils.isBlank(student.getOrgId())){
            return new ArrayList<Student>();
        }
        return studentService.findStudentByCondition(student);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Student ptStudent) {
        studentService.saveStudent(ptStudent);
        accountService.sendUserMessege(MessageTypes.USER_ADD.name(), ptStudent.getId());
        return SUCCESS_TIP;
    }

    /**
     * 删除学生数据
     *
     * @param studentId
     *          学生id
     * @param deleted
     *          是否删除
     * @return 返回
     */
    @RequestMapping(value = "/delete/{studentId}")
    @ResponseBody
    public Result delete(@PathVariable String studentId, Boolean deleted) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            accountService.deleteUser(studentId, deleted);
            //查询学生是否挂在班级上
            PtClassUser param=new PtClassUser();
            param.setUserId(studentId);
            param.setEnable(true);
            param.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear());
            PtClassUser classUser=classUserMapper.selectOne(param);
            if (classUser!=null){
                ClassUserMessage classUserVo = new ClassUserMessage();
                BeanUtils.copyProperties(classUser, classUserVo);
                classUserVo.setMessageType(MessageTypes.CLASS_STUDENT_DELETE.name());
                jmsService.sendMessage(classUserVo);
                classUserMapper.deleteById(classUser.getId());
            }
            result.setMsg("删除成功");
            logger.info("操作成功");
        } catch (Exception e) {
            logger.info("删除败", e);
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }
    /**
     * 批量删除
     *
     * @param accountIds
     *          要删除的id
     * @return JuiResult
     */
    @RequestMapping("/batchdelete")
    @ResponseBody
    public Result batchdelete(String accountIds) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (!StringUtils.isEmpty(accountIds)) {
                for (String id : accountIds.split(",")) {
                    accountService.deleteUser(id, null);
                    //查询学生是否挂在班级上
                    PtClassUser param=new PtClassUser();
                    param.setUserId(id);
                    param.setEnable(true);
                    param.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear());
                    PtClassUser classUser=classUserMapper.selectOne(param);
                    if (classUser!=null){
                        ClassUserMessage classUserVo = new ClassUserMessage();
                        BeanUtils.copyProperties(classUser, classUserVo);
                        classUserVo.setMessageType(MessageTypes.CLASS_STUDENT_DELETE.name());
                        jmsService.sendMessage(classUserVo);
                        classUserMapper.deleteById(classUser.getId());
                    }
//
                }
         }
            result.setMsg("删除成功");
            logger.info("删除成功");
        } catch (Exception e) {
            logger.info("删除失败", e);
            result.setMsg("删除失败");
        }
        return result;
    }
    /**
     * 修改学生数据
     *
     * @param student
     *          学生
     * @return 返回
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(Student student) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            studentService.updateStudent(student);
            result.setMsg("1".equals(student.getFlago()) || StringUtils.isBlank(student.getCellphone()) ? "保存成功" : "手机已被占用，可在个人中心绑定找回");
            accountService.sendUserMessege(MessageTypes.USER_UPDATE.name(), student.getId());
            logger.info("1".equals(student.getFlago()) || StringUtils.isBlank(student.getCellphone()) ? "保存成功" : "手机已被占用，可在个人中心绑定找回");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("保存失败", e);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 根据ID查找学生数据
     *
     * @param studentId
     *          学生id
     * @return 返回
     */
    @RequestMapping(value = "/get/{studentId}", method = RequestMethod.GET)
    @ResponseBody
    public Result get(@PathVariable String studentId) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            Student student = studentService.selectById(studentId);
            result.setData(student);
            logger.info("根据学生id{}查询成功", studentId);
        } catch (Exception e) {
            logger.info("查询失败", e);
            result.setCode(Result.FAIL);
            result.setMsg("查询失败");
        }
        return result;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{ptStudentId}")
    @ResponseBody
    public Object detail(@PathVariable("ptStudentId") Integer ptStudentId) {
        return studentService.selectById(ptStudentId);
    }


    /**
     * @param um
     *          搜索条件
     * @param student
     *          学生
     * @param response
     *          服务器响应
     * @param os
     *          输出对象
     */
    @RequestMapping("exportStudent")
    public void exportStudent(UserSearchModel um, Student student, HttpServletResponse response, OutputStream os) {
        try {
            String fileName = "学生用户信息表";
            if (um.getAreaId() != null) {
                String areaName = ptAreaService.selectById(um.getAreaId()).getAreaName();
                fileName = areaName + fileName;
            } else if (um.getOrgId() != null) {
                PtOrg org = ptOrgService.selectById(student.getOrgId());
                if (org != null) {
                    String areaName = ptOrgService.getAreaNameById(org.getAreaId());
                    fileName = areaName + org.getShortName() + fileName;
                }
            }
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
        } catch (UnsupportedEncodingException e) {
            logger.error("导出用户失败", e);
        }
        Map<String, Object> params = new HashMap<>();

        List<Map<Integer, String>> dataList = new ArrayList<>();

        List<ExportInfoVo> studentList = studentService.exportStuList(um);
        ExportInfoVo s = null;
        String password= Const.DEFAULT_PWD;
        for (int i = 0; i < studentList.size(); i++) {
            Map<Integer, String> dataMap = new HashMap<>();
            s = studentList.get(i);
            dataMap.put(0,s.getAccountName());
            dataMap.put(1, s.getName());
            dataMap.put(2, "学生");
            //  dataMap.put(3, SysRole.forCname(accountService.get(s.getId()).getUserType()));
            dataMap.put(4, GBSex.forCname(s.getSex()));
            dataMap.put(5,password);
            dataMap.put(6, s.getEnable() == true ? "否" : "是");
            dataMap.put(7, s.getClassName());
//      //加上学生卡号
//      dataMap.put(8,s.getStudentCardId());
            dataList.add(dataMap);
            for(Map.Entry<Integer, String> entry : dataMap.entrySet()){
                Integer mapKey = entry.getKey();
                String mapValue = entry.getValue();
                System.out.println(mapKey+":"+mapValue);
            }
        }
        params.put("data", dataList);
        params.put("userType", PtAccount.STUDENT_USER);
        StringBuilder resultMsg = null;

        batchExportUserService.exportData(os, params, resultMsg, null);
    }
}
